import React, { useState } from 'react';
import type { FormProps } from 'antd';
import { Button, Form, Input,message } from 'antd';
import { useNavigate } from 'react-router-dom';
// 使用css模块化 sass语法
import style from './login.module.scss'
import { loginApi } from '@/api/requestApi.ts'
import {addLoginData} from '@/store/modules/loginSlice'
import { useDispatch } from 'react-redux';
import loginBgImg from '@/assets/login-background.jpg'
import errorImg from '@/assets/404.jpg'
import reactImg from '@/assets/react.svg'

type FieldType = {
  account: string;
  password: string;
};

const App: React.FC = () => {
  const navigate = useNavigate()
  const dispatch = useDispatch()

  // 如何将登录成功时的状态存储在redux(RTK)中
  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    // 获取用户名和密码
    const {account,password} = values
    try {
       // 调接口
      const res = await loginApi({account,password})
      console.log(res,'res')
      // 这里将登录数据存储在了redux中
      dispatch(addLoginData({
        role:res.data.role,
        userId:res.data.userId,
        username:res.data.username
      }))
      // 判断相应状态码
      if(res && res.status === 200){
        // 登录成功时的提示信息
        message.success('登录成功')

        // 需要将服务端返回的token令牌进行本地存储
        localStorage.setItem('token',res.data.token)
        // localStorage.setItem('token','admin')

        // 等待1秒钟跳转路由
        setTimeout(()=>{
          // 跳转路由 /home
          navigate('/sys/index')
        },1000)
        
      }
      
    } catch (error) {
      message.error(error.response.data.message)
    }
  };


  // 点击登录背景图切换随机图片
  const [loginImg,setLoginImg] = useState([loginBgImg,errorImg,reactImg])

  const getRandomNumber = (): number => {
    return Math.floor(Math.random() * 3); // 返回 0 或 1 或 2
  };
  const changeBgImg = ()=>{
    console.log(style)
    document.querySelector('.'+style.container).style.backgroundImage = `url(${loginImg[getRandomNumber()]})`
    
  }


  return (
    <div className={style.container} onClick={()=>changeBgImg()}>
    <div className={style['content']}>
      <h2>文章发布系统</h2>
    <Form
    name="basic"
    labelCol={{ span: 4 }}
    wrapperCol={{ span: 18 }}
    style={{ maxWidth: 600 }}
    initialValues={{ remember: true }}
    onFinish={onFinish}
    autoComplete="off"
  >
    <Form.Item<FieldType>
      label="账号" // 设置输入框文本
      name="account" // 获取输入框数据的字段名称
      rules={[{ required: true, message: '请输入账号' }]} // 校验规则
    >
      <Input />
    </Form.Item>

    <Form.Item<FieldType>
      label="密码"
      name="password"
      rules={[{ required: true, message: '请输入密码' }]}
    >
      <Input.Password />
    </Form.Item>

    <Form.Item label={null}>
      <Button type="primary" htmlType="submit">
        登录
      </Button>
      <Button>
        取消
      </Button>
    </Form.Item>
  </Form>
    </div>
  
    </div>
  )
 
};

export default App;